package com.voxel.sense.infomsg.module.map.monitor.baseInfo;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.maps.model.Marker;
import com.example.com.common.app.BasePresenter;
import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.ListUtil;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.utils.ToastUtil;
import com.voxel.sense.infomsg.App;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.ConditionBean;
import com.voxel.sense.infomsg.data.bean.InfoWindowSiteItemBean;
import com.voxel.sense.infomsg.data.bean.MakerInfoBean;
import com.voxel.sense.infomsg.data.bean.MultiItemBean;
import com.voxel.sense.infomsg.data.bean.RealDataBean;
import com.voxel.sense.infomsg.utils.MenuDataUtil;
import com.voxel.sense.infomsg.utils.manager.QueryConfigManager;
import com.voxel.sense.infomsg.utils.marker.cluster.data.ClusterItem;
import com.voxel.sense.infomsg.utils.marker.cluster.strategy.MissionConverStrategey;
import com.voxel.sense.infomsg.view.MenuBean;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.FirmLocationEntity;
import cyy.example.com.facotry.model.api.response.FirmNameByIdEntity;
import cyy.example.com.facotry.model.api.response.MissionLocationEntity;
import cyy.example.com.facotry.model.api.response.RealDataEntity;
import cyy.example.com.facotry.model.api.response.SearchMenuEntity;
import cyy.example.com.facotry.model.api.response.StaffDetailsEntity;
import cyy.example.com.facotry.model.api.response.StaffLocationInfoEntity;
import cyy.example.com.facotry.model.api.response.TaskDetailsInfoEntity;
import cyy.example.com.facotry.model.api.response.TaskInfoEntity;
import cyy.example.com.facotry.net.RequestIdFactory;
import cyy.example.com.facotry.net.helper.FirmNetHelper;
import cyy.example.com.facotry.net.helper.NetHelper;
import cyy.example.com.facotry.net.helper.TaskNetHelper;
import cyy.example.com.facotry.share.SPEngine;

/**
 * 数据模块P层
 * Created by ChenYiYao on 2018/3/12.
 */

public class MonitorMapPresenter extends BasePresenter<MonitorMapContract.View>
        implements MonitorMapContract.Presenter, DataSource.Callback<BaseEntity> {

    private Timer mTimer;
    private String mCurrentMarkId;
    private HandlerThread mHandlerThread;
    private Handler mHandler;
    private String mCompanyName;

    public MonitorMapPresenter(MonitorMapContract.View view) {
        super(view);
    }


    @Override
    public void start() {
        mTimer = new Timer();
        long myLocationRefreshTime = SPEngine.getSPEngine().getMyLocationRefreshTime();

        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
//                ToastUtil.showToastLong(getContext(),"网络加载实时的数据");
                if (NetworkUtils.isConnected())
                    NetHelper.queryMapPeoleInfoList(MonitorMapPresenter.this);//获取人员定位列表
            }
        }, 0, myLocationRefreshTime);
        mHandlerThread = new HandlerThread("loadData");
        mHandlerThread.start();
        mHandler = new DataHandle(mHandlerThread.getLooper());
    }

    @Override
    public void destroy() {
        mTimer.cancel();
        if (mHandlerThread != null) {
            mHandlerThread.quit();
        }
        mHandler = null;
        super.destroy();
    }

    @Override
    public void doLoadStaffMenuData() {
        mView.onLoadStaffMenuData(new ArrayList<MenuBean>());
    }

    @Override
    public void getTaskList(){
        mView.onLoadTaskList(MenuDataUtil.getMissionBeanList());
    }

    @Override
    public void getLoadTaskData(){
        //获取任务列表数据
        NetHelper.queryMapTaskInfoList(this);
    }

    @Override
    public void doLoadMarkerInfo(Marker marker) {
        String title = marker.getTitle();
        ClusterItem data = (ClusterItem) marker.getObject();
        if (!NetworkUtils.isConnected()) {
            mView.showError(Factory.app().getString(R.string.network_unavailable));
        } else if (Constants.MARKER_TYPE_FIRM.equals(title)) {
            //点击公司的marker消息公司的信息窗口
            mView.showLoading("");
            FirmLocationEntity bean = (FirmLocationEntity) data.getObject();
            mCurrentMarkId = bean.getCompanyId();
            mCompanyName = bean.getCompanyName();
//            请求网络
//            NetHelper.queryMapFirmDetailInfo(mCurrentMarkId, this);
            FirmNetHelper.getFirmRealData("", mCurrentMarkId, this);
        } else if (Constants.MARKER_TYPE_PEOPLE.equals(title)) {
            //点击到其他的marker隐藏公司信息的窗口
            mView.showLoading("");
            final StaffLocationInfoEntity bean = (StaffLocationInfoEntity) data.getObject();
            mCurrentMarkId = bean.getUserId();//记录当前id
            NetHelper.searchStaffDetails(mCurrentMarkId, this);
        } else if(Constants.MARKER_TYPE_TASK.equals(title)){
            MissionLocationEntity.BodyBean bean = (MissionLocationEntity.BodyBean) data.getObject();
            getTaskDetail(bean.getTaskNumber());
        }
    }

    @Override
    public String getMarkerInfoWindowId() {
        return mCurrentMarkId;
    }


    @Override
    public void onDataLoaded(BaseEntity entity, int reqId) {
        if (mView == null)
            return;

        if (RequestIdFactory.QUERY_MAP_PEOLE == reqId) {//人员点集合请求
            List<StaffLocationInfoEntity> bean = (List<StaffLocationInfoEntity>) entity.getData();
            if (entity.isSuccess()) {
                Message message = new Message();
                message.what = DataHandle.REFRESH_STAFF_MARKER;
                message.obj = bean;
                mHandler.sendMessage(message);
            } else {
                ToastUtil.showToastLong(Factory.app(), "获取人员位置失败");
            }
        } else if (RequestIdFactory.GET_FIRM_REAL_DATA == reqId) {//公司详细信息
            mView.dimissLoading();
            if (entity.isSuccess()) {
                List<RealDataEntity> list = (List<RealDataEntity>) entity.getData();
                MakerInfoBean makerInfoBean = handlerRealData(list);
                if (makerInfoBean != null) {
                    mView.onShowMarkerFirmInfoWindow(makerInfoBean);
                } else {
                    mView.showError("暂无数据");
                }
            } else {
                mView.showError("暂无数据");
            }

        } else if (RequestIdFactory.QUERY_USER_DETAIL == reqId) {//人员详情
            mView.dimissLoading();
            if (entity.isSuccess()) {
                StaffDetailsEntity data = (StaffDetailsEntity) entity.getData();
                StaffDetailsEntity.SysUserDetailsBean sysUserDetails = data.getSysUserDetails();
                if (sysUserDetails != null && !TextUtils.isEmpty(sysUserDetails.getUserId())
                        && data.getSysUserDetails().getUserId().equals(mCurrentMarkId)) {
                    mView.onShowMarkerStaffInfoWindow(data);
                }
            }
        }else if(RequestIdFactory.QUERY_MAP_TASK == reqId){
            //获取任务列表
            if (entity.isSuccess() && entity.getData() != null) {
                List<MissionLocationEntity.BodyBean> taskEntity = (List<MissionLocationEntity.BodyBean>) entity.getData();
                Message message = new Message();
                message.what = DataHandle.TASK_LIST_KEY;
                message.obj = taskEntity;
                mHandler.sendMessage(message);


                //将任务类型id转换为文字
//                SearchMenuEntity taskType = QueryConfigManager.getInstance().getTaskType();
//                if (ob != null && ob.size() > 0 && taskType != null && taskType.getStaticSystemConstantDetails() != null &&
//                        taskType.getStaticSystemConstantDetails().size() > 0) {
//                    for (TaskInfoEntity.ObBean bean : ob) {
//                        for (SearchMenuEntity.StaticSystemConstantDetailsBean typeBean : taskType.getStaticSystemConstantDetails()) {
//                            if (typeBean != null && typeBean.getConstantCode().equals(bean.getTaskType())) {
//                                bean.setTaskTypeDesc(typeBean.getConstantName());
//                            }
//                        }
//                    }
//                }

            }
        }else if(RequestIdFactory.GET_TASK_DETAILS_INFO == reqId){
            //任务详情
            handleTaskInfo(entity);
        }
    }
    private void handleTaskInfo(BaseEntity entity) {
        if (entity.isSuccess()) {
            TaskDetailsInfoEntity infoEntity = (TaskDetailsInfoEntity) entity.getData();
            TaskDetailsInfoEntity.TaskBaseInfoVoBean taskBaseInfoVo = infoEntity.getTaskBaseInfoVo();
            String taskObjects = taskBaseInfoVo.getTaskObjects();

            //获取任务所选公司的实体
            List<FirmNameByIdEntity> firmDatas = new ArrayList<>();
//            getTaskFirmObject(taskObjects, firmDatas);

            //获取用户列表
            List<TaskDetailsInfoEntity.UserPacketBasicInfoVoBean> userList = infoEntity.getUserPacketBasicInfoVo();
            List<ConditionBean> taskUser = new ArrayList<>();
            if (!ListUtil.isEmpty(userList)) {
//                taskUser = getTakeTaskUser(userList);
            }


//            int levelPosition = getLevelPosition(taskBaseInfoVo.getTaskDegree());
//            //获取任务等级的描述文字
//            String LevelDesc = mTaskLeviesDatas.get(levelPosition).getConstantName();
//
//            int typePosition = getTypePosition(taskBaseInfoVo.getTaskType());
//            String typeDesc = mTaskTypies.get(typePosition).getConstantName();

            String type = taskBaseInfoVo.getTaskType();

            String taskContents = taskBaseInfoVo.getTaskContents();
            String taskName = taskBaseInfoVo.getTaskName();
            String endTime = taskBaseInfoVo.getEndTime();
//            mView.onRefreshView(taskName, endTime, Integer.parseInt(taskBaseInfoVo.getTaskDegree()),
//                               Integer.valueOf(taskBaseInfoVo.getTaskType()), firmDatas, taskUser, taskContents);
            mView.onRefreshViewDialog(taskBaseInfoVo);

        } else {
//            mView.onGetTaskInfoFailure("数据出错，请重新再试");
        }
    }


    /**
     * 构造公司详情窗口的数据集
     */
    private MakerInfoBean handlerRealData(List<RealDataEntity> datas) {
        //列表的数据集
        List<MultiItemBean> list = new ArrayList();
        String companyName = "";
//        RealDataEntity data = datas.get(0);
        if (datas != null && datas.size() > 0) {
            for (RealDataEntity data : datas) {
                /**
                 * 1.先提取出站位名称等数据，作为开头元素
                 * 2.站位信息之后，是站位元素的数据作为单独的条目
                 * 3.新的站位拼接在上个站位的元素最后一个
                 */
                //组装数据
                Map<String, String> analysisVo = data.getAnalysisVo();//装载数值的集合
                Map<String, String> paramNameMap = data.getParamNameMap();//装载元素名称的集合
                Map<String, String> paramUnitMap = data.getParamUnitMap();//装载单位

                if (TextUtils.isEmpty(companyName)) {
                    companyName = data.getCompanyName();
                }
                //站位信息
                InfoWindowSiteItemBean siteItemData = new InfoWindowSiteItemBean();
                siteItemData.setSiteCode(data.getSiteCode());

                if ((analysisVo != null && analysisVo.size() > 0)
                        && paramNameMap != null && paramNameMap.size() > 0
                        && paramUnitMap != null && paramUnitMap.size() > 0) {
                    RealDataBean[] realDataArry = new RealDataBean[2];
                    int ElementCount = 0;//元素个数
                    Set<String> keys = analysisVo.keySet();
                    boolean isExistSite = false;
                    for (String key : keys) {
                        //在元素数值中的集合中，在第一个字符中有个p，这里去除
                        String subKey = key.substring(1);
                        String name = paramNameMap.get(subKey);

                        //获取采集时间
                        if ("id".equals(key)) {
                            String s = analysisVo.get(key);
                            long l = TimeUtils.string2Millis(s, new SimpleDateFormat(Constants.REAL_DATA_TIME_FORMAT_TYPE));
                            String time = TimeUtils.millis2String(l);
                            siteItemData.setDatetime(time);
                            continue;
                        } else if (TextUtils.isEmpty(name)) {
                            continue;//跳过可以没有元素名称的项
                        }

                        int index = ElementCount % 2;//idnex为recycler中站位元素item的下表
                        if (ElementCount != 0 && index == 0) {
                            realDataArry = new RealDataBean[2];
                        }
                        ElementCount++;
                        String unit = paramUnitMap.get(subKey);
                        String value = analysisVo.get(key);
                        //站位元素数据
                        RealDataBean realDataBean = new RealDataBean(unit, name, 0, value, "");
                        realDataArry[index] = realDataBean;

                        if (index == 0) {
                            //首先添加站位信息，然后再添加元素信息
                            //防止添加重复的站位信息，先判断标记
                            if (!isExistSite) {
                                MultiItemBean siteItem = new MultiItemBean(siteItemData, Constants.DES_TYPE);
                                list.add(siteItem);
                                isExistSite = true;
                            }
                            //当index为0或站位的最后一个元素时，将数据封装进recycler的集合中
                            MultiItemBean itemBean = new MultiItemBean(realDataArry, Constants.OVER_DATA_TYPE);
                            list.add(itemBean);
                        }
                    }
                }
            }
        }
        //判断获取回来的公司，是否跟当前点击的公司名称一致，不一致则数据错误，不显示。若获取的公司名为空时，显示本地记录的名称
        if (!TextUtils.isEmpty(companyName) && !companyName.equals(mCompanyName)) {
            return null;
        }

        MakerInfoBean infoBean = new MakerInfoBean(mCompanyName, "", list);
        return infoBean;
    }


    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        if (mView == null)
            return;
        if (RequestIdFactory.QUERY_MAP_TASK == reqId) {

        } else if (RequestIdFactory.QUERY_MAP_PEOLE == reqId) {

        } else if (RequestIdFactory.GET_FIRM_REAL_DATA == reqId) {
            mView.dimissLoading();
            ToastUtil.showToastLong(Factory.app(), "获取公司数据信息失败");
        } else if (RequestIdFactory.QUERY_USER_DETAIL == reqId) {
            mView.dimissLoading();
            ToastUtil.showToastLong(Factory.app(), "获取人员详细信息失败");
        }
    }


    private void notifyViewAddMarker(final List datas, final String type, final Drawable drawable) {
        if (mView == null)
            return;
        ((Activity) mView).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Map<String, Drawable> icMap = new HashMap<>();
                icMap.put("7", Factory.app().getResources().getDrawable(R.mipmap.ic_zhifa));
                icMap.put("6", Factory.app().getResources().getDrawable(R.mipmap.ic_yunwei));
                icMap.put("5", Factory.app().getResources().getDrawable(R.mipmap.ic_xuancha));
                mView.onLoadMakIconFinish(icMap);

                mView.onAddMarker(datas, type, drawable);
            }
        });
    }

    //根据任务id获取数据
    public void getTaskDetail(String taskNumb){
        String roleType = QueryConfigManager.getInstance().getTaskRoleOrganizationId();
        TaskNetHelper.getTaskDetailsInfo(taskNumb, roleType, this);
    }

    @SuppressWarnings("unchecked")
    private class DataHandle extends Handler {
        static final int REFRESH_STAFF_MARKER = 1;//刷新人员的marker
        static final int REFRESH_FIRM_MARKER = 2;//刷新公司的marker
        static final int HANLDER_FIRM_REAL_DATA = 3;//处理公司的实时数据
        static final int TASK_LIST_KEY = 4;//处理任务模块

        private DataHandle(Looper looper) {
            super(looper);
        }

        List data = new ArrayList();
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case REFRESH_STAFF_MARKER:
                    Object objStaff = msg.obj;
                    data.clear();
                    if (objStaff instanceof List) {
                        List staffList = (List) objStaff;

                        if (!ListUtil.isEmpty(staffList)) {
                            //若集合中包含了自己，则需要删除。
                            for (int i = staffList.size() - 1; i >= 0; i--) {
                                StaffLocationInfoEntity entity = (StaffLocationInfoEntity) staffList.get(i);
                                if (SPEngine.getSPEngine().getUserInfo().getUser_id().equals(entity.getUserId())) {
                                    staffList.remove(i);
                                    break;
                                }
                            }
                            for(int j = 0; j < staffList.size(); j++){
                                StaffLocationInfoEntity sle = (StaffLocationInfoEntity) staffList.get(j);
                                if("5".equals(sle.getRoleId()) || "6".equals(sle.getRoleId()) ||"7".equals(sle.getRoleId())){
                                    data.add(sle);
                                }
                            }

                            Drawable drawable = App.getInstance().getApplicationContext().getResources().getDrawable(R.mipmap.ic_renyuan_press);
                            notifyViewAddMarker(data, Constants.MARKER_TYPE_PEOPLE, drawable);
                        }
                    }
                    break;
                case TASK_LIST_KEY:
                    Map<String, Drawable> icMap = new HashMap<>();
                    Object taskData = msg.obj;
                    if (taskData instanceof List) {
                        List<MissionLocationEntity.BodyBean> taskList = (List<MissionLocationEntity.BodyBean>) taskData;
                        if (!ListUtil.isEmpty(taskList)) {
//                            for(int i=0; i<taskList.size(); i++){
//                                Log.e("++++++", "卧槽杀杀杀"+taskList.get(i).getTaskTypeId());
//                                switch(i){
//                                    case 1:
                                        icMap.put("1",
                                                  App.getInstance().getApplicationContext().getResources().getDrawable(R.mipmap.ic_level_map_a));

                                        icMap.put("2",
                                                  App.getInstance().getApplicationContext().getResources().getDrawable(R.mipmap.ic_level_map_b));

                                        icMap.put("3",
                                                  App.getInstance().getApplicationContext().getResources().getDrawable(R.mipmap.ic_level_map_c));

                                        icMap.put("4",
                                                  App.getInstance().getApplicationContext().getResources().getDrawable(R.mipmap.ic_level_map_d));

                                        icMap.put("5",
                                                  App.getInstance().getApplicationContext().getResources().getDrawable(R.mipmap.ic_level_map_e));


                            }
//                        }
                        mView.onLoadMakIconFinish(icMap);
                        mView.loadDataComplete(taskList);
                    }

                    break;
            }
        }
    }
}